package arithmetic.socket.nio;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.channels.FileChannel;
import java.security.SecureRandom;

/**
 *
 * @author jiangfeng 2019/7/19 00:19
 * nio的方式实现读写
 */
public class NIODemo {
    public static void main(String[] args) throws IOException {
        //intBufferDemo();
        //nioReadFile();
        FileOutputStream fileOutputStream = new FileOutputStream("src\\main\\java\\arithmetic\\socket\\nio\\nio1.txt");
        FileChannel fileChannel = fileOutputStream.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        byteBuffer.put("helle nio world ".getBytes());

        byteBuffer.flip();
        fileChannel.write(byteBuffer);
        fileOutputStream.close();
        return;
    }

    // nio的方式 读取文件
    private static void nioReadFile() throws IOException {
        FileInputStream fileInputStream = new FileInputStream("src\\main\\java\\arithmetic\\socket\\nio\\nio.txt");
        FileChannel fileChannel = fileInputStream.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        fileChannel.read(byteBuffer);

        byteBuffer.flip();
        while ( byteBuffer.remaining()>0){
            byte b = byteBuffer.get();
            System.out.println("Character: "+(char)b);
        }
        fileInputStream.close();
    }

    /**
     * nio的方式读写
     */
    private static void intBufferDemo() {
        IntBuffer intBuffer = IntBuffer.allocate(10);// 分配一个10个位置的数组
        for (int i = 0; i < intBuffer.capacity(); i++) {
            intBuffer.put(new SecureRandom().nextInt(100));
        }
        intBuffer.flip();// 翻转下 把写状态变成读。
        while (intBuffer.hasRemaining()){
            System.out.println(intBuffer.get());
        }
    }
}
